package com.everydayflash.flar.mustang {
	import net.hires.debug.Stats;
	
	import com.everydayflash.flar.sample.pv3d.PV3DARApp;
	
	import org.papervision3d.Papervision3D;
	import org.papervision3d.events.FileLoadEvent;
	import org.papervision3d.materials.BitmapMaterial;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.primitives.Plane;
	
	import flash.display.StageAlign;
	import flash.display.StageQuality;
	import flash.display.StageScaleMode;
	import flash.events.Event;	

	[SWF(width=640,height=480,frameRate=30,backgroundColor=0x0)]

	public class FlarMustang extends PV3DARApp {

		[Embed(source="assets/camera.dat", mimeType="application/octet-stream")]
		private var FLARCameraDatFile:Class;
		
		[Embed(source="assets/ev.patt", mimeType="application/octet-stream")]
		private var FlarPattFile:Class;

		private var mustang:Mustang;
		
		[Embed (source="assets/shadow.png")]
		private var ShadowGraphic:Class;
		private var shadow:Plane;

		private var driver:Driver;
		private var mustangLoaded:Boolean = false;
		private var mustangHolder:DisplayObject3D;

		public function FlarMustang() {
			stage.quality = StageQuality.LOW;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.showDefaultContextMenu = false;
			stage.stageFocusRect = false;
			
			Papervision3D.useDEGREES = false; // = use radians

			init(new FLARCameraDatFile(), new FlarPattFile(), 640, 480);

			var sh:BitmapMaterial = new BitmapMaterial(new ShadowGraphic().bitmapData);
			sh.precise = true;
			sh.tiled = true;
			sh.smooth = false;
			shadow = new Plane(sh, 150, 80, 5, 5);
			shadow.rotationX = Math.PI / 2;	
			
			mustang = new Mustang();
			mustang.addEventListener(FileLoadEvent.LOAD_COMPLETE, onMustang);
			
			mustangHolder = new DisplayObject3D();
			mustangHolder.addChild(shadow);
			mustangHolder.addChild(mustang);
			mustangHolder.rotationX = Math.PI / 2;
			
			_baseNode.addChild(mustangHolder);
			
			addChild(new Stats());
		}

		private function onMustang(event:FileLoadEvent):void {
			driver = new Driver(stage, mustang);
			shadow.y = mustang.base * 10 + 5;
			driver.speed = 0;
			
			mustangLoaded = true;
		}
		
		override protected function render(e:Event = null):void {
			if(mustangLoaded) {
				mustang.turn(driver.turnAmount, driver.speed);
				mustang.drive(driver.moveAmount.negate(), driver.orientation, driver.direction * -1, driver.brake, driver.handBrake);
			}
			
			shadow.x = mustang.x;
			shadow.z = mustang.z;
			shadow.rotationY = mustang.rotationY;

			super.render(e);
		}
	}
}